package cloud.seri.auth.service

import cloud.seri.auth.domain.Dept
import cloud.seri.auth.repository.DeptRepository
import cloud.seri.auth.service.dto.DeptDTO
import cloud.seri.auth.service.mapper.DeptMapper
import net.dreamlu.mica.core.result.R
import org.slf4j.LoggerFactory
import org.springframework.data.domain.Sort
import org.springframework.stereotype.Service
import java.util.*

/**
 * Service Implementation for managing [Dept].
 */
@Service
class DeptService(
    val deptRepository: DeptRepository,
    val deptMapper: DeptMapper
)
{

    private val log = LoggerFactory.getLogger(DeptService::class.java)

    /**
     * Save a dept.
     *
     * @param deptDTO the entity to save.
     * @return the persisted entity.
     */
    fun save(deptDTO: DeptDTO): R<DeptDTO>?
    {
        log.debug("Request to save Dept : {}", deptDTO)
        var dept = deptMapper.toEntity(deptDTO)
        dept = deptRepository.save(dept)
        return R.success(deptMapper.toDto(dept))
    }

    /**
     * Get all the depts.
     *
     * @return the list of entities.
     */
    fun findAll(): List<DeptDTO>
    {
//        val depts = deptRepository.findAll(Sort.by("sort")).map { deptMapper.toDto(it) }
//        val p = depts.filter { it.parentId == null }
        return deptRepository.findAll(Sort.by("sort")).map { deptMapper.toDto(it) }
    }

//    private fun getChildren(p: List<DeptDTO>, menus: List<DeptDTO>): List<DeptDTO>
//    {
//        p.forEach { menu ->
//            menu.children = menus.filter { it.parentId == menu.id }
//            if (menu.children?.isNotEmpty())
//            {
//                getChildren(menu.children, menus)
//            }
//        }
//        return p
//    }

    /**
     * Get one dept by id.
     *
     * @param id the id of the entity.
     * @return the entity.
     */
    fun findOne(id: String): DeptDTO?
    {
        log.debug("Request to get Dept : {}", id)
        return deptRepository.findById(id)
            .map(deptMapper::toDto)
            .orElseThrow { Throwable("没找到") }
    }

    /**
     * Delete the dept by id.
     *
     * @param id the id of the entity.
     */
    fun delete(id: String)
    {
        log.debug("Request to delete Dept : {}", id)
        deptRepository.deleteById(id)
    }
}
